package com.zx.dsptuneup_TriMic.fragment;


import android.graphics.PorterDuff;
import android.graphics.PorterDuffColorFilter;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import com.h6ah4i.android.widget.verticalseekbar.VerticalSeekBar;
import com.h6ah4i.android.widget.verticalseekbar.VerticalSeekBarWrapper;
import com.zx.dsptuneup_TriMic.App;
import com.zx.dsptuneup_TriMic.Base.BaseFragment;
import com.zx.dsptuneup_TriMic.Data_Bean.EqSegmentBean;
import com.zx.dsptuneup_TriMic.Enum.MessageReceiveType;
import com.zx.dsptuneup_TriMic.ProtocolTools.ProtocolConversion;
import com.zx.dsptuneup_TriMic.R;
import com.zx.dsptuneup_TriMic.Tools.CVIPaperDialogUtils;
import com.zx.dsptuneup_TriMic.Tools.ChannelIndexConvert;
import com.zx.dsptuneup_TriMic.Tools.EventMessage;
import com.zx.dsptuneup_TriMic.Util.ClickUtil;
import com.zx.dsptuneup_TriMic.Util.Constants;
import com.zx.dsptuneup_TriMic.Util.UserUtil;
import com.zx.dsptuneup_TriMic.bean.BasicResponse;
import com.zx.dsptuneup_TriMic.network.DefaultObserver;
import com.zx.dsptuneup_TriMic.network.NetWorkManager;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * A simple {@link Fragment} subclass.
 */
public class InputEQFragment extends BaseFragment implements View.OnClickListener {
    @BindView(R.id.linear)
    LinearLayout mLinear;

    @BindView(R.id.restoreEqBtn)
    Button restorebtn;

    @BindView(R.id.button1)
    Button button1;

    @BindView(R.id.button2)
    Button button2;

    @BindView(R.id.button3)
    Button button3;

    private Button currentSelBtn = null;
    private View rootView;
    private String TAG = "InputEQFragment";
    private int currentSelTitleIndex = Constants.channelEnum.line1;       //  头部标签选择

    private int[][] qArrArr = {{0,0,0,0,0,0,0,0,0,0},{0,0,0,0,0,0,0,0,0,0},{0,0,0,0,0,0,0,0,0,0},{0,0,0,0,0,0,0,0,0,0},
            {0,0,0,0,0,0,0,0,0,0},{0,0,0,0,0,0,0,0,0,0},{0,0,0,0,0,0,0,0,0,0},{0,0,0,0,0,0,0,0,0,0},{0,0,0,0,0,0,0,0,0,0},
            {0,0,0,0,0,0,0,0,0,0},{0,0,0,0,0,0,0,0,0,0},{0,0,0,0,0,0,0,0,0,0},{0,0,0,0,0,0,0,0,0,0},{0,0,0,0,0,0,0,0,0,0}};

    private int[] userChannelArr = {Constants.channelEnum.line1,Constants.channelEnum.line3,
            Constants.channelEnum.line5,Constants.channelEnum.line7, Constants.channelEnum.line8,
            Constants.channelEnum.line9,Constants.channelEnum.line13};                             // 对应普通用户通道数据
    // 10段固定的频率值
    private final int[] qValueArr ={0,0,0,0,0,0,0,0,0,0}; // 固定的q值
    SeekBar[] seekBarFinal = new SeekBar[10];

    public InputEQFragment() {
        setFragmentTitle("11");
    }


    public void setCurrentSelTitleIndex(int currentSelTitleIndex) {
        this.currentSelTitleIndex = currentSelTitleIndex;
    }

    /**
     *  收到消息
     * */
    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onGetStickyEvent(EventMessage message) {
        Log.d(TAG,"onReceiveMsg====" + message.toString());
        if (message.getType().equals(MessageReceiveType.InputTitleIndexChange)){
            this.currentSelTitleIndex = Integer.parseInt(message.getMessage());
            refreshUI();

        }else if(message.getType().equals(MessageReceiveType.MessageRecInput)){
            refreshUI();
        }
    }

    /**
     *  刷新UI
     * */
    private void refreshUI() {
        int posotion = ChannelIndexConvert.convertIndex(currentSelTitleIndex);
        List<Double> eqGainArr = new ArrayList<>();
        for (int i=0;i< App.getEqData().getInputChannelArr().get(posotion).getEqSegArr().size();i++ ){
            EqSegmentBean eqSegmentBean = App.getEqData().getInputChannelArr().get(posotion).getEqSegArr().get(i);
//            qArr.add(eqSegmentBean.getEqSegName());
            eqGainArr.add(eqSegmentBean.getGain());
        }
        Log.e(TAG,"eqGainArr==="+  eqGainArr);
        for(int i=0;i<10;i++){
            // 设置frequent
            double eqGain = eqGainArr.get(i);
            if(seekBarFinal[i] != null){
                seekBarFinal[i].setProgress( (int)eqGain +10);
            }
        }
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void initVariables(Bundle bundle) {

    }

    @Override
    protected View initView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (null != rootView) {
            ViewGroup parent = (ViewGroup) rootView.getParent();
            if (null != parent) {
                parent.removeView(rootView);
            }
        } else {
            rootView = inflater.inflate(R.layout.fragment_input_eq, container, false);
            ButterKnife.bind(this, rootView);
            EventBus.getDefault().register(this);
            setupData();
        }
        return rootView;
    }

    private void setupData() {
        //        String[] eqarr = {"32","64","128","256","512","1024","2048","4096","8192","16384"};
//        int[] eqIntArr = {32,64,128,256,512,1024,2048,4096,8192,16384};

        int posotion = ChannelIndexConvert.convertIndex(currentSelTitleIndex);
        List<String> qArr = new ArrayList<>();
        List<Integer> eqIntArr = new ArrayList<>();
        for (int i=0;i< App.getEqData().getInputChannelArr().get(posotion).getEqSegArr().size();i++ ){
            EqSegmentBean eqSegmentBean = App.getEqData().getInputChannelArr().get(posotion).getEqSegArr().get(i);
            qArr.add(eqSegmentBean.getEqSegName());

            eqIntArr.add(Integer.parseInt(eqSegmentBean.getEqSegName()));
        }

        //  eq恢复默认
        restorebtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                if(currentSelEQButton==button5||currentSelEQButton==button6||currentSelEQButton==button7||currentSelEQButton==button8){
//                    ToastUtils.showToast(activity,"自定义按钮暂时不可恢复!");
//                    return;
//                }
                CVIPaperDialogUtils.showCustomDialog(getActivity(), "确定要恢复默认EQ配置吗", null, "确定", true, new CVIPaperDialogUtils.ConfirmDialogListener() {
                    @Override
                    public void onClickButton(boolean clickConfirm, boolean clickCancel) {
                        if (clickConfirm){
                            new  Thread(new Runnable() {
                                @Override
                                public void run() {
                                    for(int i=0;i<10;i++){
                                        seekBarFinal[i].setProgress(qValueArr[i]+10);
                                        int frequent = eqIntArr.get(i);
                                        double q_value = 1.41;

                                        double gain = (double) qValueArr[i];
                                        final int equalizerIndex = i;

                                        int posotion = ChannelIndexConvert.convertIndex(currentSelTitleIndex);
                                        App.getContext().getEqData().getInputChannelArr().get(posotion).getEqSegArr().get(equalizerIndex).setGain(gain);

                                        HashMap map = new HashMap();
                                        map.put("groups", UserUtil.currentSingleGroup);
                                        map.put("type", Constants.element_typeEnum.INPUT);
                                        map.put("channel",userChannelArr[currentSelTitleIndex]);
                                        map.put("line", equalizerIndex);
                                        map.put("frequency", frequent);
                                        map.put("gain", gain);
                                        map.put("q", q_value);

                                        //查询指定音频处理器数据

                                        NetWorkManager.getInstance().getNetWorkApiService().setEQ(map).compose(InputEQFragment.this.<BasicResponse<String>>bindToLifecycle())
                                                .subscribeOn(Schedulers.io())
                                                .observeOn(AndroidSchedulers.mainThread())
                                                .subscribe(new DefaultObserver<BasicResponse<String>>() {
                                                    @Override
                                                    protected void onSuccess(BasicResponse<String> response) {
                                                        if (response != null) {
                                                            Log.e(TAG,"data==="+response.getData());
                                                        }
                                                    }
                                                    @Override
                                                    protected void onFail(BasicResponse<String> response) {
                                                        super.onFail(response);

                                                    }
                                                    @Override
                                                    public void onError(@NonNull Throwable e) {
                                                        super.onError(e);
                                                    }
                                                });

//                                        App.getContext().getProtocolConversion().setEQ(ProtocolConversion.getFrameId(),Constants.operation_typeEnum.set_device,Constants.element_typeEnum.INPUT,userChannelArr[currentSelTitleIndex],equalizerIndex,frequent,q_value,gain);
                                        try {
                                            Thread.sleep(100);
                                        }catch (Exception e){

                                        }
                                    }

                                }
                            }).start();

                        }
                    }
                });
            }
        });
        button1.setVisibility(View.GONE);
        //  男声发送eq
        button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(currentSelBtn == button1){
                    return;
                }
                button1.setSelected(true);
                if(currentSelBtn != null){
                    currentSelBtn.setSelected(false);
                }

                currentSelBtn = button1;


                //  发送eq增益调节指令
                int frequent = 5000;
                double q_value = 1.41;
                double gain = -10;

//                button1.setSelected(!button1.isSelected());

//                for(){
//
//                }
//                App.getContext().getProtocolConversion().setEQ(ProtocolConversion.getFrameId(),Constants.operation_typeEnum.set_device,Constants.element_typeEnum.INPUT,developChannelArr[currentSelTitleIndex],currentSelFreqIndex,frequent,q_value,gain);
            }
        });
        button2.setVisibility(View.GONE);
        //  女声发送eq
        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(currentSelBtn == button2){
                    return;
                }
                button2.setSelected(true);
                if(currentSelBtn != null){
                    currentSelBtn.setSelected(false);
                }
                currentSelBtn = button2;

            }
        });

        button3.setVisibility(View.GONE);
        button3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(currentSelBtn == button3){
                    return;
                }
                button3.setSelected(true);
                if(currentSelBtn != null){
                    currentSelBtn.setSelected(false);
                }
                currentSelBtn = button3;


            }
        });



        for(int i = 0;i<10;i++){
            LinearLayout row = new LinearLayout(getActivity());
            LinearLayout.LayoutParams lLayoutlayoutParams = new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.WRAP_CONTENT,
                    LinearLayout.LayoutParams.MATCH_PARENT);
            row.setLayoutParams(lLayoutlayoutParams);
            row.setOrientation(LinearLayout.VERTICAL);

            mLinear.addView(row);
            TextView toptext = new TextView(getActivity());
            LinearLayout.LayoutParams toplay = new LinearLayout.LayoutParams(
                    dp2px(50),
                    LinearLayout.LayoutParams.WRAP_CONTENT);
            toptext.setLayoutParams(toplay);
            toptext.setTextColor(getResources().getColor(R.color.white));
            toptext.setTextSize(12);
            toptext.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
            toptext.setGravity(View.TEXT_ALIGNMENT_CENTER);
            toplay.weight = 1;
            toptext.setText(qArr.get(i));
            row.addView(toptext);

            VerticalSeekBarWrapper wrap = new VerticalSeekBarWrapper(getActivity());
            LinearLayout.LayoutParams wraplay = new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.MATCH_PARENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT);

            wraplay.setMargins(10,20,10,10);
            wrap.setLayoutParams(wraplay);
            wraplay.weight = 34;
            row.addView(wrap);

            VerticalSeekBar seekBar = new VerticalSeekBar(getActivity());
            LinearLayout.LayoutParams seekbarlay = new LinearLayout.LayoutParams(0,0);
            seekBar.setMax(20);
            seekBar.setProgress(qValueArr[i]+10);
            seekBar.setLayoutParams(seekbarlay);
            seekBar.setThumb(getResources().getDrawable(R.drawable.custom_equalizer_thumb));
            seekBar.setRotationAngle(VerticalSeekBar.ROTATION_ANGLE_CW_270);
            seekBar.getProgressDrawable().setColorFilter(new PorterDuffColorFilter(getResources().getColor( R.color.segmnet_select), PorterDuff.Mode.SRC_IN));
            wrap.addView(seekBar);

            seekBarFinal[i] = seekBar;
            TextView bottomtext = new TextView(getActivity());
            LinearLayout.LayoutParams bottomlay = new LinearLayout.LayoutParams(
                    dp2px(50),
                    LinearLayout.LayoutParams.WRAP_CONTENT);
            bottomtext.setLayoutParams(bottomlay);
            bottomlay.weight = 1;
            bottomtext.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
            bottomtext.setTextColor(getResources().getColor(R.color.white));
            bottomtext.setTextSize(12);
            bottomtext.setGravity(View.TEXT_ALIGNMENT_CENTER);

            bottomtext.setText(qValueArr[i]+ " DB");
            row.addView(bottomtext);

            final int equalizerIndex = i;
            seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
                @Override
                public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                    bottomtext.setText(progress-10+" DB");
                    if(fromUser){}
                }

                @Override
                public void onStartTrackingTouch(SeekBar seekBar) {

                }

                @Override
                public void onStopTrackingTouch(SeekBar seekBar) {
                    Log.d(TAG,"滑动停止");
//                    int[] qArr = qArrArr[currentSelTitleIndex];
//                    qArr[equalizerIndex] = seekBar.getProgress()-10;
//                    qArrArr[currentSelTitleIndex] = qArr;

                    //  如果保存按钮不显示，不可以存eqtacticArr
                    // 策略存储
//                    if(currentSelEQIndex>=0 && SaveEqBtn.getVisibility()==View.VISIBLE){
//                        eqtacticArr[currentSelEQIndex][equalizerIndex] = seekBar.getProgress()-10;
//                    }

                    int posotion = ChannelIndexConvert.convertIndex(currentSelTitleIndex);


                    //  发送增益调节指令
                    int frequent = eqIntArr.get(equalizerIndex);
                    double q_value = 1.41;

                    double gain = (double) seekBar.getProgress()-10;
                    App.getContext().getEqData().getInputChannelArr().get(posotion).getEqSegArr().get(equalizerIndex).setGain(gain);

                    HashMap map = new HashMap();
                    map.put("groups", UserUtil.currentSingleGroup);
                    map.put("type", Constants.element_typeEnum.INPUT);
                    map.put("channel",userChannelArr[currentSelTitleIndex]);
                    map.put("line", equalizerIndex);
                    map.put("frequency", frequent);
                    map.put("gain", gain);
                    map.put("q", q_value);

                    //查询指定音频处理器数据

                    NetWorkManager.getInstance().getNetWorkApiService().setEQ(map).compose(InputEQFragment.this.<BasicResponse<String>>bindToLifecycle())
                            .subscribeOn(Schedulers.io())
                            .observeOn(AndroidSchedulers.mainThread())
                            .subscribe(new DefaultObserver<BasicResponse<String>>() {
                                @Override
                                protected void onSuccess(BasicResponse<String> response) {
                                    if (response != null) {
                                        Log.e(TAG,"data==="+response.getData());
                                    }
                                }
                                @Override
                                protected void onFail(BasicResponse<String> response) {
                                    super.onFail(response);

                                }
                                @Override
                                public void onError(@NonNull Throwable e) {
                                    super.onError(e);
                                }
                            });

//                    App.getContext().getProtocolConversion().setEQ(ProtocolConversion.getFrameId(),Constants.operation_typeEnum.set_device,Constants.element_typeEnum.INPUT,userChannelArr[currentSelTitleIndex],equalizerIndex,frequent,q_value,gain);
                }
            });
            //  下面代码要加，一开始收到event信息时seekbar还没有初始化
            refreshUI();
        }
    }

    /**
     * dp转换成px
     */
    public int dp2px(float dpValue){
        float scale=getResources().getDisplayMetrics().density;
        return (int)(dpValue*scale+0.5f);
    }


    @Override
    public void onClick(View v) {
        if (ClickUtil.isFastClick(1000, v)) {
            return;
        }
    }
}